<template>
  <div class="employee-workhours">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else>
      <!-- 员工选择器 -->
      <div class="employee-selector">
        <el-select
          v-model="selectedEmployees"
          multiple
          filterable
          placeholder="请选择员工姓名或工号"
          @change="handleEmployeeChange"
        >
          <el-option
            v-for="item in employeeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <el-button type="primary" @click="loadData">查询</el-button>
      </div>
      
      <!-- 统计摘要卡片 -->
      <div class="summary-cards" v-if="statistics.summary">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <h3>员工数量</h3>
                </div>
              </template>
              <div class="card-value">{{ statistics.summary.total_employees }}</div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <h3>工作天数</h3>
                </div>
              </template>
              <div class="card-value">{{ statistics.summary.total_work_days }}</div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <h3>白班工时</h3>
                </div>
              </template>
              <div class="card-value">{{ statistics.summary.total_day_work_hours }} 小时</div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <h3>加班工时</h3>
                </div>
              </template>
              <div class="card-value">{{ statistics.summary.total_overtime_hours }} 小时</div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 加班类型详情 -->
        <el-card class="overtime-details" v-if="Object.keys(statistics.summary.overtime_by_type || {}).length > 0">
          <template #header>
            <div class="card-header">
              <h3>加班类型详情</h3>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6" v-for="(hours, type) in statistics.summary.overtime_by_type" :key="type">
              <div class="overtime-type-item">
                <div class="overtime-type-label">{{ getOvertimeTypeLabel(String(type)) }}</div>
                <div class="overtime-type-value">{{ hours }} 小时</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>
      
      <!-- 员工工时统计表格 -->
      <el-card class="employee-table" v-if="statistics.data && statistics.data.length > 0">
        <template #header>
          <div class="card-header">
            <h3>员工工时统计</h3>
          </div>
        </template>
        
        <el-table :data="statistics.data" border stripe style="width: 100%" height="400" max-height="400">
          <el-table-column prop="employee_id" label="工号" width="100" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="dept1" label="部门" width="150" />
          <el-table-column prop="total_work_days" label="工作天数" width="100" />
          <el-table-column prop="day_total_work_hours" label="白班工时" width="100">
            <template #default="scope">
              {{ scope.row.day_total_work_hours?.toFixed(1) || 0 }} 小时
            </template>
          </el-table-column>
          <el-table-column prop="overtime_hours" label="加班工时" width="100">
            <template #default="scope">
              {{ scope.row.overtime_hours?.toFixed(1) || 0 }} 小时
            </template>
          </el-table-column>
          <el-table-column label="加班详情" min-width="200">
            <template #default="scope">
              <div v-if="Object.keys(scope.row.overtime_details || {}).length > 0">
                <div v-for="(hours, type) in scope.row.overtime_details" :key="type" class="overtime-detail-item">
                  {{ getOvertimeTypeLabel(String(type)) }}: {{ hours.toFixed(1) }} 小时
                </div>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click="showDailyDetails(scope.row)"
                :disabled="!scope.row.daily_records || scope.row.daily_records.length === 0"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 每日详情对话框 -->
      <el-dialog
        v-model="dailyDetailsVisible"
        :title="`${currentEmployee?.name || ''} 考勤详情`"
        width="80%"
      >
        <el-table :data="currentEmployee?.daily_records || []" border stripe style="width: 100%">
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="weekday" label="星期" width="80" />
          <el-table-column prop="day_total_work_hours" label="白班工时" width="100">
            <template #default="scope">
              {{ scope.row.day_total_work_hours?.toFixed(1) || 0 }} 小时
            </template>
          </el-table-column>
          <el-table-column prop="night_work_hours" label="晚班工时" width="100">
            <template #default="scope">
              {{ scope.row.night_work_hours?.toFixed(1) || 0 }} 小时
            </template>
          </el-table-column>
          <el-table-column prop="overtime_hours" label="加班工时" width="100">
            <template #default="scope">
              {{ scope.row.overtime_hours?.toFixed(1) || 0 }} 小时
            </template>
          </el-table-column>
          <el-table-column prop="overtime_type" label="加班倍率" width="100">
            <template #default="scope">
              {{ scope.row.overtime_type || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="attendance_type" label="考勤类型" min-width="150" />
        </el-table>
      </el-dialog>
      
      <!-- 无数据提示 -->
      <el-empty 
        v-if="!loading && (!statistics.data || statistics.data.length === 0) && selectedEmployees.length > 0" 
        description="未找到考勤数据" 
      />
      
      <el-empty 
        v-if="!loading && selectedEmployees.length === 0" 
        description="请选择员工" 
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, defineExpose } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { employeeApi } from '@/axios/api/employees'
// API基础URL
const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
const API_PREFIX = '/api/statistics'

// 接收父组件传递的属性
const props = defineProps({
  startDate: {
    type: String,
    required: true
  },
  endDate: {
    type: String,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  }
})

interface Employee {
  employee_id: string;
  name: string;
  affiliation: string;
  dept1: string;
  dept2: string;
  dept3: string;
  position: string;
  hire_date: string;
  leave_date?: string;
}

interface EmployeeOption {
  value: string;
  label: string;
}

interface DailyRecord {
  date: string;
  weekday: string;
  day_total_work_hours: number;
  night_work_hours: number;
  overtime_hours: number;
  overtime_type: number;
  attendance_type: string;
}

interface EmployeeStatisticsData {
  employee_id: string;
  name: string;
  affiliation: string;
  dept1: string;
  dept2: string;
  dept3: string;
  position: string;
  total_work_days: number;
  day_total_work_hours: number;
  night_work_hours: number;
  overtime_hours: number;
  overtime_details: { [key: string]: number };
  daily_records: DailyRecord[];
}

interface EmployeeStatisticsSummary {
  total_employees: number;
  total_work_days: number;
  total_day_work_hours: number;
  total_night_work_hours: number;
  total_overtime_hours: number;
  overtime_by_type: { [key: string]: number };
  period: string;
}

interface EmployeeStatistics {
  data: EmployeeStatisticsData[];
  summary: EmployeeStatisticsSummary | null;
}

// 状态变量
const loading = ref(false)
const selectedEmployees = ref<string[]>([])
const employeeOptions = ref<EmployeeOption[]>([])
const statistics = ref<EmployeeStatistics>({ data: [], summary: null })
const dailyDetailsVisible = ref(false)
const currentEmployee = ref<EmployeeStatisticsData | null>(null)

// 页面挂载时获取所有员工
onMounted(async () => {
  console.log('员工工时统计组件挂载')
  try {
    console.log('开始获取员工列表')
    const response = await employeeApi.getEmployees() as unknown as Employee[]
    // const response = await axios.get<Employee[]>('/api/employees')
    console.log('API响应:', response)
    console.log('response.data 类型:', typeof response)
    // 确保 response.data 是一个数组，如果不是，则默认为空数组
    employeeOptions.value = Array.isArray(response) ? response.map(emp => ({
      value: emp.employee_id,
      label: `${emp.name}（${emp.employee_id}）`
    })) : []
    
    // 组件挂载后自动加载所有员工的工时统计数据
    loadData()
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  }
})

// 处理员工选择变化
const handleEmployeeChange = () => {
  console.log('选中的员工:', selectedEmployees.value)
}

// 加载员工工时统计数据
const loadData = async () => {
  if (selectedEmployees.value.length === 0) {
    // 如果未选择员工，则获取所有员工数据
    console.log('未选择员工，将获取所有员工数据')
  }
  
  loading.value = true
  try {
    const response = await axios.post<EmployeeStatistics>(`${BASE_URL}${API_PREFIX}/employee-workhours`, {
      employee_ids: selectedEmployees.value.length > 0 ? selectedEmployees.value : [], // 空数组表示获取所有员工
      start_date: props.startDate,
      end_date: props.endDate
    })
    
    statistics.value = response.data
    console.log('员工工时统计数据:', statistics.value)
  } catch (error) {
    console.error('获取员工工时统计数据失败:', error)
    ElMessage.error('获取员工工时统计数据失败')
  } finally {
    loading.value = false
  }
}

// 显示员工每日详情
const showDailyDetails = (employee: EmployeeStatisticsData) => {
  currentEmployee.value = employee
  dailyDetailsVisible.value = true
}

// 获取加班类型标签
const getOvertimeTypeLabel = (type: string) => {
  const typeMap: { [key: string]: string } = {
    '0': '无加班',
    '1.5': '1.5倍工资',
    '2': '2倍工资',
    '3': '3倍工资'
  }
  return typeMap[type] || `${type}倍工资`
}

// 监听日期变化
watch(
  () => [props.startDate, props.endDate],
  () => {
    // 无论是否选择了员工，日期变化时都重新加载数据
    loadData()
  }
)

// 向父组件暴露的方法
defineExpose({
  loadData
})
</script>

<style scoped>
.employee-workhours {
  padding: 20px 0;
  height: calc(100vh - 200px);
  overflow: auto;
}

.employee-selector {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.employee-selector .el-select {
  flex: 1;
}

.summary-cards {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  text-align: center;
}

.overtime-details {
  margin-top: 20px;
}

.overtime-type-item {
  text-align: center;
  padding: 10px;
}

.overtime-type-label {
  font-size: 14px;
  color: #606266;
}

.overtime-type-value {
  font-size: 18px;
  font-weight: bold;
  color: #F56C6C;
}

.employee-table {
  margin-top: 20px;
  max-height: calc(100vh - 350px);
  overflow: hidden;
}

/* 确保表格内容溢出时显示滚动条 */
.employee-table :deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

.overtime-detail-item {
  margin-bottom: 5px;
}

.loading-container {
  padding: 20px;
}
</style> 